var express = require('express');
var router = express.Router();
const  crypto = require('crypto');
const md5 = crypto.createHash('md5');
//获取域名
    function UrlRegEx(url)
    {
        //如果加上/g参数，那么只返回$0匹配。也就是说arr.length = 0
        var re = /(\w+):\/\/([^\:|\/]+)(\:\d*)?(.*\/)([^#|\?|\n]+)?(#.*)?(\?.*)?/i;
        //re.exec(url);
        var arr = url.match(re);
        return (arr[1]+"://"+arr[2]+"/");
    }
//base32
let base32 = [
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
    'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
    'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
    'y', 'z', '0', '1', '2', '3', '4', '5'
    ];
    //生成短链接字段
function longUrlToShortUrl(inputs) {
  let hexs = md5.update(inputs).digest('hex');
  let hexsLen = hexs.length;
  let subhexsLen = hexsLen / 8;
  let ptintoutput = [];
  for (let i = 0; i < subhexsLen; i++) {
    let subhexs = hexs.substring(i * 8, 8);
    let change = 0x3FFFFFFF & (1 * ('0x'+subhexs));
    let ptintout = '';
    let short_url = UrlRegEx(inputs);
    for (let j = 0; j < 6; j++) {
      let strs = 0x0000001F & change;
      ptintout += base32[strs];
      change = change >> 5;
    }
    short_url += ptintout;
    ptintoutput.push(short_url);

  }
  ptintoutput.splice(1,1);
  return ptintoutput;
}
let res = longUrlToShortUrl('http://www.cnblogs.com/zemliu/helloworld');
console.log(res);
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title:'短链接'});
});

module.exports = router;
